import { Component, OnInit } from '@angular/core';
import { NzModalRef, NzMessageService } from 'ng-zorro-antd';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MarketFansService } from '@core/routes-services/market-fans.service';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Observable } from 'rxjs/Observable';
import { debounceTime, map, switchMap } from 'rxjs/operators';

@Component({
  selector: 'app-market-fans-change-parent',
  templateUrl: './change-parent.component.html',
})
export class MarketFansChangeParentComponent implements OnInit {
  entity: any = {};
  validateForm: FormGroup;
  isLoading: boolean = false;
  loadingOption: boolean = false;

  searchChange$ = new BehaviorSubject('');
  fansList: any [] = [];

  constructor(private fb: FormBuilder,
              private modal: NzModalRef,
              private marketFansService: MarketFansService,
              public message: NzMessageService) {
  }

  ngOnInit(): void {
    if(this.entity.parentId){
      this.fansList.push({id:this.entity.parentId,name:this.entity.parentName});
    }
    this.initValidateForm();

    const searchFanOptions = (name: string) => this.marketFansService.searchOptions(name).then((res) => {
      if (res.status.toString().startsWith('20')) {
        return res.data.content;
        // this.page = res.data;
        // ++this.page.number;
      } else {
        this.message.warning(res.message);
        return [];
      }
    }, error => {
      this.message.error(error.message ? error.message : error.error);
      return [];
    });
    const optionList$: Observable<string[]> = this.searchChange$.asObservable().pipe(debounceTime(500)).pipe(switchMap(searchFanOptions));
    optionList$.subscribe(data => {
      console.log(data)
      this.fansList = data;

      if(this.entity.parentId){
        if(this.fansList.findIndex((r)=>r.id == this.entity.parentId) == -1){
          this.fansList.push({id:this.entity.parentId,name:this.entity.parentName});
        }
      }
      this.loadingOption = false;
    });
  }


  initValidateForm() {
    //角色: 1-业务员，2-渠道商，3-门店，4-代理
    this.validateForm = this.fb.group({
      name: [this.entity.name, [Validators.required, Validators.maxLength(30)]],
      parentId: [this.entity.parentId, []],
    });

  }
  onSearch(value: string): void {
    this.loadingOption = true;
    this.searchChange$.next(value);
  }

  submitForm(): void {
    if (this.validateForm.invalid) {
      for (const i in this.validateForm.controls) {
        this.validateForm.controls[i].markAsDirty();
        this.validateForm.controls[i].updateValueAndValidity();
      }
    } else {
      this.isLoading = true;
      this.marketFansService.changeParent(this.entity.id, this.validateForm.value).then((res) => {
        if (res.status.toString().startsWith('20')) {
          this.modal.close(true);
        } else {
          this.message.warning(res.message);
        }
        this.isLoading = false;
      }, error => {
        this.message.error(error.message ? error.message : error.error);
        this.isLoading = false;
      });
    }
  }

  close() {
    this.modal.destroy();
  }
}
